//
//  HomeViewController.m
//  ZYTS-iPhone
//
//  Created by yuzhou on 12-12-6.
//  Copyright (c) 2012年 wzyk. All rights reserved.
//

#import "HomeViewController.h"
#import "FeaturedBookCell.h"
#import "BookViewController.h"
#import "AudioPlayer.h"
#import "SearchViewController.h"
#import "MobClick.h"

@interface HomeViewController ()
{
    BOOL requesting;
}
@end

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotFeatured:) name:gotFeaturedNotify object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotAd:) name:gotAdNotify object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePlayerBar) name:kPlayerStateDidChange object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDisplay) name:UIApplicationDidBecomeActiveNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDisplay) name:kConnectionEnable object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UMOnlineConfigDidFinished:) name:UMOnlineConfigDidFinishedNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateAppLogo) name:UIApplicationDidBecomeActiveNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideAppLogo) name:UIApplicationDidEnterBackgroundNotification object:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    featuredTableView.alpha = 0;
    if (adViewController == nil) {
        adViewController = [[AdViewController alloc] initWithNibName:@"AdViewController" bundle:nil];
//        featuredTableView.tableHeaderView = adViewController.view;
    }
    [self updatePlayerBar];
    [self updateDisplay];
    [MobClick updateOnlineConfig];
}

- (void)updateDisplay
{
    if ([self isViewLoaded] && !requesting) {
        if (_featuredArray == nil) {
            [self showLoadingView];
            requesting = YES;
            [[DataRequest sharedRequest] getFeatured];
        }
        if (adViewController.adArray == nil) {
            [[DataRequest sharedRequest] getAd];
        }
    }
}

- (void)updatePlayerBar {
    // 判断是否正在播放
    if ([CollectionData hasContent:kCollection_playing]) {
        if (playerBarView) {
            return;
        }

        playerBarView = [[[NSBundle mainBundle] loadNibNamed:@"PlayerBarView" owner:self options:nil] objectAtIndex:0];
        CGRect frameTable = featuredTableView.frame;
        CGRect frameBar = playerBarView.frame;
        frameBar.origin.x = frameTable.origin.x;
        frameBar.origin.y = frameTable.origin.y;
        playerBarView.frame = frameBar;
        [self.view addSubview:playerBarView];
        
        frameTable.origin.y += PlayerBarHeight;
        frameTable.size.height -= PlayerBarHeight;
        featuredTableView.frame = frameTable;
    }
    else if (playerBarView) {
        [playerBarView removeFromSuperview];
        playerBarView = nil;
        
        CGRect frameTable = featuredTableView.frame;
        frameTable.origin.y -= PlayerBarHeight;
        frameTable.size.height += PlayerBarHeight;
        featuredTableView.frame = frameTable;
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [adViewController startAutoScroll];
}

- (void)gotFeatured:(NSNotification *)notification
{
    [self removeloadingView];
    requesting = NO;
    NSDictionary *response = notification.object;
    if (response) {
        NSArray *array = [response valueForKey:@"result"];
        if (array) {
            self.featuredArray = array;
            [featuredTableView reloadData];
            [UIView animateWithDuration:0.3 animations:^{
                featuredTableView.alpha = 1;
            }];
        }
    }
}

- (void)gotAd:(NSNotification *)notification
{
    if ([notification.object isKindOfClass:[NSDictionary class]]) {
        NSArray *adArray = [notification.object valueForKey:@"result"];
        if ([adArray isKindOfClass:[NSArray class]] && adArray.count > 0) {
            featuredTableView.tableHeaderView = adViewController.view;
            [adViewController showAds:adArray];
        }
    }
}

- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.featuredArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"FeaturedBookCell";
    FeaturedBookCell *cell = (FeaturedBookCell *)[featuredTableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"FeaturedBookCell" owner:self options:nil] objectAtIndex:0];
    }
    cell.bookInfo = [self.featuredArray objectAtIndex:indexPath.row];
    [cell updateDisplay];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 94;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *bookInfo = [self.featuredArray objectAtIndex:indexPath.row];
    BookViewController *bookViewController = [[[BookViewController alloc] initWithNibName:@"BookViewController" bundle:nil] autorelease];
    bookViewController.itemid = [bookInfo valueForKey:@"item_id"];
    bookViewController.itemname = [bookInfo valueForKey:@"item_name"];
    
    UINavigationController *navController = (UINavigationController *)self.view.window.rootViewController;
    [navController pushViewController:bookViewController animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    float scrollerOffsetTop = 180 - featuredTableView.contentOffset.y;
    scrollerOffsetTop = scrollerOffsetTop < 0 ? 0 : scrollerOffsetTop;
    featuredTableView.scrollIndicatorInsets = UIEdgeInsetsMake(scrollerOffsetTop, 0, 0, 0);
}

- (IBAction)showSearchView:(id)sender
{
    SearchViewController *searchViewController = [[[SearchViewController alloc] initWithNibName:@"SearchViewController" bundle:nil] autorelease];
    
    UINavigationController *navController = (UINavigationController *)self.view.window.rootViewController;
    [navController pushViewController:searchViewController animated:YES];
}

- (void)showLoadingView
{
    if (loadingView.superview) {
        return;
    }
    if (loadingView == nil) {
        loadingView = [[[ABSpringLoadingView alloc] initWithFrame:featuredTableView.frame] autorelease];
    }
    loadingView.alpha = 0;
    [self.view addSubview:loadingView];
    [UIView animateWithDuration:0.3 animations:^{
        loadingView.alpha = 1;
    }];
}

- (void)removeloadingView
{
    if (loadingView) {
        [UIView animateWithDuration:0.3 animations:^{
            loadingView.alpha = 0;
        } completion:^(BOOL finished) {
            [loadingView removeFromSuperview];
            loadingView = nil;
        }];
    }
}

- (void)UMOnlineConfigDidFinished:(NSNotification *)notification
{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"UMOnlineConfigDidFinished:%@",notification.userInfo);
        if ([[notification.userInfo objectForKey:@"InAppReview"] isEqualToString:@"YES"]) {
            [UIView animateWithDuration:0.5 delay:0.5 options:UIViewAnimationCurveEaseInOut animations:^{
                logoImageView.alpha = 1;
                appLabel.alpha = 0;
                
                CGRect rect = logoImageView.frame;
                rect.origin.x = 100;
                logoImageView.frame = rect;
                
                rect = appLabel.frame;
                rect.origin.x = 168;
                appLabel.frame = rect;
            } completion:nil];
        }
    });
}

- (void)updateAppLogo
{
    if ([self isViewLoaded]) {
        [MobClick updateOnlineConfig];
    }
}

- (void)hideAppLogo
{
    logoImageView.alpha = 0;
    appLabel.alpha = 1;
    
    CGRect rect = logoImageView.frame;
    rect.origin.x = 0;
    logoImageView.frame = rect;
    
    rect = appLabel.frame;
    rect.origin.x = 68;
    appLabel.frame = rect;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [featuredTableView release];
    [_featuredArray release];
    [logoImageView release];
    [appLabel release];
    [super dealloc];
}
- (void)viewDidUnload {
    [featuredTableView release];
    featuredTableView = nil;
    [logoImageView release];
    logoImageView = nil;
    [appLabel release];
    appLabel = nil;
    [super viewDidUnload];
}
@end
